<template>
    <div class="wxChat">
        <div class="wxMain">
            <!-- 左侧用户列表 -->
            <div class="wxUserListBox">
                <div class="wxUserListSearch">
                    <input 
                        type="text" placeholder="搜索" class="wxUserListSearchInput"
                        v-model="searchInput"
                        @input="searchUserChatList"/>
                    <span class="wxUserListSearchBtn">S</span>
                </div>
                <div class="wxUserList">
                    <friend-list :friendChatList="showFriendChatList" @selectedFriendChatEmit="selectedFriendChatHandler"/>
                </div>
            </div>
            <!-- 右侧聊天框 -->
            <div class="wxChatBox"
                @mousedown="wxMainMouseDown" 
                @mousemove="wxMainMouseMove" 
                @mouseup="wxMainMouseUp" 
                @mouseleave="wxMainMouseLeave">
                <div class="wxChatHeader">
                    <div class="wxChatUser">{{ selectedFriendChat.name }}</div>
                </div>
                <div class="wxChatContent" @scroll="wxChatContentScroll" ref="wxChatContent">
                    <chat-list :chatList="chatList"></chat-list>
                </div>

                <div class="wxDragLine" ref="wxDragLine"></div>
                <div class="wxChatInput" 
                    ref="wxChatInput"
                    @keydown="prevnetDefaultNewLine"
                    @keyup.enter="submitMsgHandler"
                    >
                    <textarea v-model="msgInput" v-if="this.selectedFriendChat.uniqueId ? 'disabled': ''"></textarea>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import ChatList from '@/components/ChatList.vue';
import FriendList from '@/components/FriendList.vue';
import { instance } from '@/socketio';
import { getURLParams } from "@/utils/param";
export default {
    name: 'WxChat',
    components: {
        ChatList,
        FriendList
    },
    created(){
        const params = getURLParams();
        const token = params.id || this.$store.getters.token;
        this.selfUserInfo.uniqueId = token || '0';

        instance.on('chat', obj => {
            console.log('接收chat', obj);
            const selectedUniqueId = this.selectedFriendChat && this.selectedFriendChat.uniqueId || '';
            const uniqueId = obj.fromUniqueId;
            const content = obj.content;
            const time = new Date(obj.timestamp);

            if(!this.uniqueId2ChatListMap[uniqueId]){
                this.uniqueId2ChatListMap[uniqueId] = {
                    scrollTo: 0,
                    chatList: []
                };
            }

            this.updateChatList({
                uniqueId,
                content,
                time,
            }, 'left', selectedUniqueId === uniqueId);

            const friendInfo = this.friendChatList.find(item=>item.uniqueId === uniqueId) || {};
            // 更新用户列表最新发言等信息
            this.updateFriendChatList({
                uniqueId: friendInfo.uniqueId,
                name: friendInfo.name,
                dateTime: time.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}),
                lastMsg: content,
                avatar: friendInfo.avatar || 'xiaoxin.jpeg',
            });
        });

        instance.on('errorChat', obj => {
            console.log('errorChat', obj);
        });

        // 初始化显示的好友用户聊天列表
        this.showFriendChatList = this.friendChatList;
    },
    data() {
        return {
            pressInfo: {
                isPress: false,
                y: 0,
                height: 0,
            },
            // 聊天记录列表
            chatList: [], // 临时值
            // 通过uniqueId区分不同用户的聊天记录
            uniqueId2ChatListMap: {
                // '1': {
                //     scrollTo: 0,
                //     chatList:[{
                //         avator: 'xiaoxin.jpeg',
                //         msg: '你好',
                //         time: '2025-02-02 12:23:34',
                //         direction: 'left'  // left | right
                //     }]
                // },
                // '2': {
                //     scrollTo:0,
                //     chatList:[{
                //         avator: 'xiaoxin.jpeg',
                //         msg: '你好2',
                //         time: '2025-02-02 12:23:34',
                //         direction: 'left'  // left | right
                //     }]
                // },
                // '3': {
                //     scrollTo: 0,
                //     chatList: [{
                //         avator: 'xiaoxin.jpeg',
                //         msg: '你好sdjflk十多多文本多多文本换行<br/>\n\n多多文本多多文本多多文本多多文本多多文本多多文本多多文本多多文本多多文本',
                //         time: '2025-02-02 12:23:34',
                //         direction: 'left'  // left | right
                //     }]
                // },
            },
            // 显示的好友用户聊天列表，用户搜索时使用
            showFriendChatList: [], 
            // 好友用户聊天列表
            friendChatList: [{
                uniqueId: '1',
                name: '1张三asdfajksdjfas d 啊水淀粉',
                dateTime: '19:27',
                lastMsg: '你好',
                avatar: 'xiaoxin.jpeg',
                unreadCount: 2,
                state: 1,
            },{
                uniqueId: '2',
                name: '2李四',
                dateTime: '20:37',
                lastMsg: '你好0时代发生的水淀粉',
                avatar: 'xiaoxin.jpeg',
                unreadCount: 2,
                state: 1,
            },{
                uniqueId: '3',
                name: '3王五',
                dateTime: '20:37',
                lastMsg: '你好0时代发生的水淀粉',
                avatar: 'xiaoxin.jpeg',
                unreadCount: 2,
                state: 1,
            }],
            // 选中的聊天用户
            selectedFriendChat: {},
            // 自己用户信息
            selfUserInfo: {
                uniqueId: '0',
                name: '我自己',
                avatar: 'xiaoxin.jpeg',
            },
            // 输入的消息
            msgInput: '',
            // 搜索输入内容
            searchInput: '',
        };
    },
    methods: {
        wxMainMouseDown(e) {
            if(e.target.classList.contains('wxDragLine')){
                this.pressInfo.isPress = true;
                this.pressInfo.y = e.pageY;
                const wxChatInput = this.$refs['wxChatInput'];
                this.pressInfo.height = wxChatInput ? wxChatInput.getBoundingClientRect().height : 0;
            }
        },
        wxMainMouseMove(e) {
            if(!this.pressInfo.isPress){
               return;
            }
            const wxChatInput = this.$refs['wxChatInput'];
            if(wxChatInput){
                wxChatInput.style.height = (this.pressInfo.height + this.pressInfo.y - e.pageY) + 'px';
                window.document.body.style.cursor = 'row-resize';
            }
            const wxDragLine = this.$refs['wxDragLine'];
            if(wxDragLine){
                wxDragLine.style.height = '2px';
            }
        },
        wxMainMouseUp() {
            this.cancelMoveDragLine();
        },
        // 鼠标移出区域
        wxMainMouseLeave() {
            this.cancelMoveDragLine();
        },
        // 聊天内容滚动
        wxChatContentScroll(e){
            const scrollTop = e.target.scrollTop;
            const uniqueId =this.selectedFriendChat && this.selectedFriendChat.uniqueId || '';
            if(uniqueId && this.uniqueId2ChatListMap[uniqueId]){
                this.uniqueId2ChatListMap[uniqueId].scrollTo = scrollTop;
            }
        },
        // 取消拖动
        cancelMoveDragLine(){
            this.pressInfo.isPress = false;
            window.document.body.style.cursor = 'default';
            const wxDragLine = this.$refs['wxDragLine'];
            if(wxDragLine){
                wxDragLine.style.height = '1px';
            }
        },

        // 子组件传递过来的选中聊天用户
        selectedFriendChatHandler(item){
            if(!item || !item.uniqueId){
                return;
            }
            if(this.selectedFriendChat && this.selectedFriendChat.uniqueId === item.uniqueId){
                return;
            }
            this.selectedFriendChat = item;
            this.chatList = this.uniqueId2ChatListMap[item.uniqueId]&&this.uniqueId2ChatListMap[item.uniqueId].chatList || [];
            this.$nextTick(()=>{
                const wxChatContent = this.$refs['wxChatContent'];
                if(wxChatContent && this.uniqueId2ChatListMap[item.uniqueId]){
                    wxChatContent.scrollTop = this.uniqueId2ChatListMap[item.uniqueId].scrollTo || 0;
                }
            });
            // 清空未发送的消息内容
            this.msgInput = '';
        },
        // 阻止回车换行
        prevnetDefaultNewLine(e){
            if(e.key === 'Enter' && !e.shiftKey){
                e.preventDefault();
            }
        },
        // 提交消息
        submitMsgHandler(e){
            if((e.key === 'Enter' && e.shiftKey) || (this.msgInput.trim() === '')){
                return;
            }
            e.stopPropagation();
            e.preventDefault();
            if(this.selectedFriendChat && this.selectedFriendChat.uniqueId){
                const uniqueId = this.selectedFriendChat.uniqueId;
                const time = new Date();
                const content = this.msgInput;
                this.updateChatList({
                    uniqueId: uniqueId,
                    content: this.msgInput,
                    time: time,
                }, 'right',true);

                // 发送人唯一ID
                const selfUniqueId = this.selfUserInfo.uniqueId;
                instance.emit('chat', {
                    toUniqueId: uniqueId,
                    content: content,
                    fromUniqueId: selfUniqueId,
                });

                this.msgInput = '';

                // 更新用户列表最新发言等信息
                this.updateFriendChatList({
                    uniqueId: this.selectedFriendChat.uniqueId,
                    name: this.selectedFriendChat.name,
                    dateTime: time.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}),
                    lastMsg: content,
                    avatar: this.selectedFriendChat.avatar || 'xiaoxin.jpeg',
                });
            }
        },
        // 更新用户列表最新发言等信息
        updateFriendChatList(friendChatInfo){
            const index = this.friendChatList.findIndex(item=>item.uniqueId === friendChatInfo.uniqueId);
            if(index > -1){
                this.friendChatList[index].dateTime = friendChatInfo.dateTime;
                this.friendChatList[index].lastMsg = friendChatInfo.lastMsg;
            }else{
                this.friendChatList.unshift({
                    uniqueId: friendChatInfo.uniqueId,
                    name: friendChatInfo.name,
                    dateTime: friendChatInfo.dateTime,
                    lastMsg: friendChatInfo.lastMsg,
                    avatar: friendChatInfo.avatar || 'xiaoxin.jpeg',
                    unreadCount: 1,
                    state: 1,
                });
            }
        },
        // 更新聊天列表
        updateChatList(chatInfo, direction, isCurrentSelected){
            const {uniqueId, content, time} = chatInfo;

            if(!this.uniqueId2ChatListMap[uniqueId]){
                this.uniqueId2ChatListMap[uniqueId] = {
                    scrollTo: 0,
                    chatList: []
                };
            }
            this.uniqueId2ChatListMap[uniqueId].chatList.push({
                avator: this.selfUserInfo.avatar,
                msg: content,
                time: time.toLocaleString(),
                direction,  // left | right
            });

            // 如果是当前选中的用户，则更新聊天列表
            if(isCurrentSelected && this.$refs['wxChatContent']){
                this.chatList = this.uniqueId2ChatListMap[uniqueId].chatList;
                const wxChatContent = this.$refs['wxChatContent'];
                // 只有在接近底部时，才自动滚动到底部
                // 防止在查看历史消息时，发送消息导致滚动到底部
                const needScrollToBottom = Math.abs(wxChatContent.scrollHeight-wxChatContent.scrollTop-wxChatContent.clientHeight) <= 10;
                this.$nextTick(()=>{ // 等待dom更新完成后执行
                    if(needScrollToBottom){
                        wxChatContent.scrollTop = wxChatContent.scrollHeight;
                    }
                });
            }
        },
        // 搜索用户聊天列表
        searchUserChatList(){
            const keyword = this.searchInput.trim().toLowerCase();
            if(!keyword){
                this.showFriendChatList = this.friendChatList;
                return;
            }
            this.showFriendChatList = this.friendChatList.filter(item=>{
                return item.name.toLowerCase().includes(keyword) || item.lastMsg.toLowerCase().includes(keyword);
            });
        },
    },
    beforeCreate(){
        instance.off('chat');
        instance.off('errorChat');
    },
}
</script>

<style scoped>
.wxChat{
    height: 100%;
}
.wxMain {
    display: flex;
    height: 100%;
}
/* 左侧用户列表 */
.wxUserListBox{
    display: flex;
    flex-direction: column;
    width: 260px;
}
.wxUserList {
    width: 100%;
    background: var(--wxUserListBackground);
    height: 100%;
    overflow-y: scroll;
}
.wxUserListSearch{
    height: 60px;
    padding: 10px 5px;
    box-sizing: border-box;
    background: var(--wxUserListSearchBackground);
    display: flex;
    align-items: center;
}
.wxUserListSearchInput{
    width: 100%;
    height: 40px;
    line-height: 40px;
    padding: 0 15px;
    box-sizing: border-box;
    border: 1px solid #ddd;
    border-radius: 4px;
    outline: none;
    font-size: 14px;
    margin-right: 5px;
}
.wxUserListSearchBtn{
    width: 30px;
    height: 30px;
    min-width: 30px;
    max-width: 30px;
    line-height: 30px;
    text-align: center;
    background: var(--wxUserListSearchBtnBackground);
    color: var(--wxUserListSearchBtnColor);
    border-radius: 4px;
    cursor: pointer;
}
/* 右侧聊天框 */
.wxChatBox{
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%;
}
.wxChatHeader{
    height: 60px;
    background: var(--wxChatHeaderBackground);
    line-height: 60px;
    min-height: 60px;
    padding-left: 20px;
}
.wxChatContent{
    flex: 1;
    background: var(--wxChatContentBackground);
    overflow-y: scroll;
    min-height: 100px;
    padding-bottom: 10px;
    border-top: 1px solid var(--wxChatContentBorderTopColor);
}
.wxDragLine{
    height: 1px;
    background: var(--wxDragLineBackground);
    cursor: row-resize;
    min-height: 1px;
}
.wxChatInput{
    height: 200px;
    min-height: 200px;
    width: 100%;
    /* 同wxChatInput textarea颜色 */
    background: var(--wxChatInputTextareaBackground);
}
.wxChatInput textarea{
    height: calc(100% - 5px);
    /* 同wxChatInput颜色 */
    background: var(--wxChatInputTextareaBackground);
    box-sizing: border-box;
    padding: 10px;
    overflow: auto;
    outline: none;
    border: navajowhite;
    resize: none;
    width: 100%;
    margin-top: 5px;
}
</style>